package com.qzimp.fujiancuo.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.qzimp.fujiancuo.entity.Email;
import com.qzimp.fujiancuo.entity.dto.CaptchaInfo;
import com.qzimp.fujiancuo.entity.vo.ResultCode;
import com.qzimp.fujiancuo.entity.vo.ResultVo;
import com.qzimp.fujiancuo.exceptions.ApiException;
import com.qzimp.fujiancuo.service.AdminService;
import com.qzimp.fujiancuo.service.EmailService;
import com.qzimp.fujiancuo.utils.CaptchaRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@Api(tags = "邮箱验证码")
@RequestMapping("/auth2")
@Slf4j
public class CaptchaController {
    @Value("${mycuo.default-salt}")//通过配置获取数据 EL标签 ${key}
    private String salt;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private AdminService adminService;

    @Autowired
    private EmailService emailService;
    private static final String CAPTCHA_SESSION_KEY = Constants.KAPTCHA_SESSION_KEY;

    @ApiOperation("发送验证码到邮箱")
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        try {
            // 生成文字验证码
            String text = defaultKaptcha.createText();
            // 生成一个唯一标识，用于关联本次验证码请求
            String captchaId = UUID.randomUUID().toString();
            // 创建CaptchaInfo对象保存验证码相关信息及设置过期时间
            CaptchaInfo captchaInfo = new CaptchaInfo(text, captchaId);
            HttpSession session = request.getSession();
            session.setAttribute(CAPTCHA_SESSION_KEY, captchaInfo);

            // 生成图片验证码（原功能保留，若不需要图片验证码可移除相关代码）
            BufferedImage image = defaultKaptcha.createImage(text);
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);

            // 发送验证码到邮箱（假设下面的sendValidateCode2方法已调整为合适的参数传递形式，这里简化示例）
            sendValidateCode2("17379209737@163.com", text, captchaId);

            // 保存验证码信息到模拟存储库（可替换为更可靠的存储方式）
            CaptchaRepository.saveCaptcha(captchaInfo);
        } catch (Exception e) {
            // 记录详细错误日志（假设使用了日志框架，如log4j、slf4j等）
            log.error("生成验证码或发送到邮箱出现异常", e);
            // 设置错误响应状态码为500，表示服务器内部错误
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                // 返回一个错误提示图片（简单示例，可根据实际情况优化）
                BufferedImage errorImage = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2d = errorImage.createGraphics();
                g2d.setColor(Color.RED);
                g2d.setFont(new Font("Arial", Font.BOLD, 16));
                g2d.drawString("验证码生成或发送失败", 50, 50);
                g2d.dispose();
                ServletOutputStream out = response.getOutputStream();
                ImageIO.write(errorImage, "jpg", out);
            } catch (IOException ex) {
                log.error("返回错误提示图片失败", ex);
            }
        }
    }

    /*发送邮件*/
    public ResultVo sendValidateCode2(String mail, String text, String captchaId) {
        if (StringUtils.isEmpty(mail)) {
            throw new ApiException(ResultCode.CUSTOM_ERROR, "接收者邮箱不能为空");
        }

        try {
            Email email = new Email();
            String[] emails = {mail};
            email.setUser(emails);
            email.setSubject("邮箱验证码");
            // 修改邮件内容，将验证码文本和captchaId都包含进去，方便用户查看和后续使用
            email.setContent("您的验证码是：" + text + "，验证码标识为：" + captchaId);
            emailService.sendMail(email);
            return new ResultVo(ResultCode.SUCCESS);
        } catch (Exception e) {
            // 记录详细错误日志
            log.error("邮件发送失败", e);
            throw new ApiException(ResultCode.CUSTOM_ERROR, "发送失败");
        }
    }

    // 新增验证验证码是否正确的方法
    @ApiOperation("验证验证码")
    @GetMapping("/verifyCaptcha")
    public ResultVo verifyCaptcha(String captchaId, String inputCode, HttpServletRequest request) {
        CaptchaInfo captchaInfo = CaptchaRepository.getCaptcha(captchaId);
        if (captchaInfo!= null && captchaInfo.getCaptchaText().equals(inputCode)
                && new Date().before(captchaInfo.getExpirationTime())) {
            return new ResultVo(ResultCode.SUCCESS);
        }
        return new ResultVo(ResultCode.CUSTOM_ERROR);
    }

}